<!--
 * @Author: wangding
 * @Date: 2020-11-02 15:46:49
 * @LastEditTime: 2021-05-24 14:42:25
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \solaxcloud\src\views\device\inverter\index.vue
-->
<template>
    <div class="inverter-main-box">
        <div class="search-box">
            <div class="search-box-sub">
                <span class="lable-text">{{$t('sn.wifiSN')}}</span>
                <el-input style="width:160px;" v-big v-model="querylist.pileSn" :placeholder="$t('device.inverter.SN')"></el-input>
            </div>
            <div class="search-box-sub">
                <span class="lable-text">{{$t('site.siteName')}}</span>
                <el-input style="width:160px;" v-model="querylist.siteName" :placeholder="$t('pleaseInput')"></el-input>
            </div>
            <div class="search-box-sub">
                <span class="lable-text">{{$t('user.loginName')}}</span>
                <el-input style="width:160px;" v-model="querylist.loginName" :placeholder="$t('pleaseInput')"></el-input>
            </div>
            <div class="search-box-sub">
                <span class="lable-text">{{$t('devWifi.wifiSN')}}</span>
                <el-input style="width:160px;" v-big v-model="querylist.wifiSn" :placeholder="$t('pleaseInput')"></el-input>
            </div>
            <div class="search-box-sub">
                <span class="lable-text">{{$t('device.inverter.enableFlag')}}</span>
                <el-select v-model="querylist.onLineStatus" filterable :placeholder="$t('pleaseSelect')" :clearable='true'>
                    <el-option
                    v-for="item in textDataList.ON_LINE_STATE"
                    :key="item.value"
                    :label="item.code"
                    :value="item.value">
                    </el-option>
                </el-select>
            </div>
            <div class="search-box-sub">
                <span class="lable-text">{{$t('device.inverter.nation')}}</span>
                <el-select v-model="querylist.nation" filterable :placeholder="$t('pleaseSelect')" :clearable='true'>
                    <el-option
                    v-for="item in countryList"
                    :key="item.enName"
                    :label="item.enName"
                    :value="item.enName">
                    </el-option>
                </el-select>
            </div>
            <div class="search-box-sub">
                <span class="lable-text">{{$t('inventoryManage.type')}}</span>
                <el-select v-model="querylist.pileType" filterable :placeholder="$t('pleaseSelect')" :clearable='true'>
                    <el-option
                    v-for="item in deviceTypeData"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id">
                    </el-option>
                </el-select>
            </div>
            <!-- <div class="search-box-sub" v-if='userType == 2'>
                <span class="lable-text">{{$t('device.subscription.group')}}</span>
                <el-select v-model="querylist.subGroupId" filterable :placeholder="$t('pleaseSelect')" :clearable='true'>
                    <el-option
                    v-for="item in groupName"
                    :key="item.sid"
                    :label="item.groupName"
                    :value="item.sid">
                    </el-option>
                </el-select>
            </div> -->
            <div class="search-box-sub">
                <el-button type="primary" @click='query'>{{$t('query')}}</el-button>
                <el-button v-if='userType == 1 || userType == 2' type="primary" @click='exportModalNew'>{{$t('export')}}</el-button>
                <el-button v-else  type="primary" @click='exportModal'>{{$t('export')}}</el-button>
            </div>
        </div>
        <baseTable v-loading="loading"  row-key='sid' :data="dataRows" border  stripe :column='column' @getpage='deviceGetPage'>
            <template #SN="{data}">
                <a href="javascript:;" class="hover-a-link" style="color:#ED7523;" @click='openSnDetail(data)'>{{data.pileSn}}</a>
            </template>
            <template #pileType="{data}">
                {{comm.returnCode(textDataList.WIFI_DEVICE_CHARGE_TYPE,data.moduleType,'value','code')}}
            </template>
            <template #enableFlag="{data}">
                <span :style='data.onLineStatus==1?"color:#429dff":""'>
                    <i class="iconfont icon-wifi" style="vertical-align: middle;" ></i>
                    {{returnStatus(data.onLineStatus)}}
                </span>
            </template>
            <!-- 更新进度！！！ -->
            <template #progress="{data}">
                <span>{{returnProgress(data)}}</span>
            </template>
            <template #option="{data}">
                <div class="option-box">
                    <!-- v-if='userType == 2 || userType == 5'  数据权限设置-->
                    <el-button size='small' type="primary" icon="el-icon-s-tools"  @click='showFlowModal(data)'  :title="$t('device.inverter.js_role_setting')" ></el-button>
                    
                    <!-- v-if='data.deviceType == 1 && userType ==5'  备用密码查询-->
                    <el-button  size='small' type="primary" icon="el-icon-unlock"  @click='showPasswordModal(data)'  :title='$t("devWifi.passwordQuery")'></el-button>
                    
                    <!-- v-if='userType==5' 解绑 -->
                    <el-popconfirm
                        :title="$t('device-confirm-untie')"
                        :confirm-button-text="$t('sure')"
                        :cancel-button-text="$t('cancel')"
                        @confirm='wifiUnbundlingWifiSN(data)'
                    >
                        <el-button size='small' type="primary" icon="el-icon-crop" slot="reference"  :title='$t("devWifi.unbundling")'></el-button>
                    </el-popconfirm>

                    <!-- <el-button style='font-size:18px;' type="" icon='el-icon-upload' :title="$t('devWifi.upgrade')" @click='showEditModal(data)' v-if='comm.returnFlagAd(2)'></el-button> -->

                    <!-- 升级 -->
                    <el-button size='small' type="primary" icon='el-icon-upload' :title="$t('devWifi.upgrade')"  v-if='userType == 2 || userType == 1'  @click='upgrade(data)'></el-button>
                    <!-- 取消升级 -->
                    <el-button style='font-size:18px;'  v-if='data.updateFlag == 1 && data.onLineStatus == 1' type="" icon='el-icon-refresh-left' :title="$t('reset.button')" @click='wifiEditEntity(data)'></el-button>
                </div>
            </template>
        </baseTable>
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>
        <flowModal :flowModalWifuSn='flowModalWifuSn' :textDataList='textDataList'></flowModal>
        <remarkModal :remarkModalWifuSn='remarkModalWifuSn' :remarkModalNote='remarkModalNote' @uploadData='query'></remarkModal>
        <setGroupModal :groupRowData='groupRowData'  ></setGroupModal>
        <pvModules :modulesRowData='modulesRowData' @uploadData='query'></pvModules>
        <importModal :querylist='querylist'></importModal>

        <upgradeModal @uploadData='query' :deviceClassify='textDataList.CHARGE_DEVICE_CLASSIFY' :editWifiSn='editWifiSn' :rowEditData= 'rowEditData' v-if="visibleUpgrade"></upgradeModal>
    </div>
</template>

<script>
import baseTable from '../../../../components/common/baseTable'
import moment from 'moment'
import flowModal from '../flowModal'
import remarkModal from '../remark'
import setGroupModal from '../setGroup'
import pvModules from '../pvModules'
import importModal from '../import'
import upgradeModal from './upgrade'
export default {
    components: {
        baseTable,
        flowModal,
        remarkModal,
        setGroupModal,
        pvModules,
        importModal,
        upgradeModal
    },
    props: {

    },
    data() {
        return {
            siteId:this.$route.query.siteId,
            userId:this.$route.query.userId,
            businessId:this.$route.query.businessId,
            querylist:{
                pileSn:'',
                siteName:'',
                loginName:'',
                wifiSn:'',
                onLineStatus:'',
                nation:'',
                pileType:'',
                // pileType:'',
                // subGroupId:'',
                // isSub:1,
                // currentTime:moment().format("YYYY-MM-DD"),
            },
            size:10,
            current:1,
            statusList:[],
            countryList:[],
            textDataList:{},
            groupName:[],
            loading:false,
            dataRows:[],
            column:[{
                title: 'SN',
                value: 'pileSn',
                slot: 'SN'
            },
            {
                title: this.$t('devWifi.wifiSN'),
                value: 'wifiSn',
                slot: 'wifiSN',
            },
            {
                title: this.$t('devWifi.deviceType'),
                value: 'moduleType',
                slot: 'pileType'
            }
            // ,{
            //     title: this.$t('device.inverter.ratedPower'),
            //     value: 'ratedPower',
            //     slot: 'ratedPower',
            //     min_width:"110"
            // }
            ,{
                title: this.$t('totalPower.InverterPower.siteId'),
                value: 'siteName',
                slot: 'siteName',
            },
            {
                title: this.$t('user.loginName'),
                value: 'loginName',
                slot: 'loginName'
            }
            // ,{
            //     title: this.$t('test.deviceTest.real_time.todayYield') + '(kWh)',
            //     value: 'todayYield',
            //     slot: 'todayYield',
            //     min_width:"150"
            // },{
            //     title: this.$t('test.deviceTest.real_time.totalYield') + '(kWh)',
            //     value: 'totalYield',
            //     slot: 'totalYield',
            //     min_width:"150"
            // },
            ,{
                title: this.$t('m_497927264244072448'),
                value: 'onLineStatus',
                slot: 'enableFlag'
            },{
                title: this.$t('devWifi.accessTime'),
                value: 'accessTime',
                slot: 'accessTime',
            },{
                title: this.$t('devUpgrade.upgradeStatus'),
                value: 'progress',
                slot: 'progress',
            },{
                title: this.$t('opttask.option'),
                value: 'sid',
                slot: 'option',
            }],
            total:1,
            flowModalWifuSn:'',
            remarkModalWifuSn:'',
            remarkModalNote:'',
            groupRowData:{},
            modulesRowData:{},
            deviceTypeData:[{
                text:'EV Charger',
                id:'0'
            }],
            editWifiSn:'',
            rowEditData:{},
            updatingSNsArr:[],//升级的
            doUpdataArr:[],
            timeOutId: null,//定时器
        };
    },
    computed: {
        userType(){
            return localStorage.getItem('userType')
        },
        visibleUpgrade(){
            return this.$store.state.sysStore.visibleUpgrade
        }
    },
    watch: {

    },
    created() {
       if(this.$route.query.siteName){
            this.querylist.siteName = this.$route.query.siteName
        }
        this.selectCountry()
        this.getDictionaryBatch()
        this.deviceGetSubGroupName()
    },
    beforeDestroy(){
        //页面销毁前清除计时器
        window.clearTimeout(this.timeOutId)
    },
    mounted() {
        
    },
    methods: {
        //升级
        upgrade(data){
            // this.editInverter=data.inverterType
            this.editWifiSn = data.wifiSn
            this.rowEditData = data
            console.log(data,'升级')
            this.$store.commit('setVisibleUpgrade',true)
        },
        async showPasswordModal(data){
            let res = await this.API.snGetPassword({
                wifiSN:data.wifiSn
            })
            if(res){
                this.$confirm(this.$t('backup_password')+':'+res)
                .then(_ => {
                    done();
                })
                .catch(_ => {});
            }else{
                this.comm.showMsg(false)
            }
        },
        async exportModalNew(){
            let res = await this.API.deviceCheckCount(this.querylist)
            if(res > 20){
                this.comm.showMsg(false,this.$t('download.count_lt_20'))
            }else if(res == 0){
                this.comm.showMsg(false,this.$t('download.count_is_zero'))
            }else{
                this.$store.commit('setDictionaryVisible',true)
            }
        },
        async wifiUnbundlingWifiSN(data){
            let res = await this.API.devchargepileUnbundlingWifiSN({
                wifiSNs:data.wifiSn
            })
            if(this.comm.showMsg(res.success)){
                this.deviceGetPage()
            }
        },
        exportModal(){
            this.comm.windowOpen('/device/inverterExcel',{
                sn:this.querylist.SN,
                siteName:this.querylist.siteName,
                loginName:this.querylist.loginName,
                wifiSN:this.querylist.wifiSN,
                enableFlag:this.querylist.enableFlag,
                inverterType:this.querylist.inverterType,
                // inverterType:this.querylist.inverterType,
                // inverterType:this.querylist.inverterType,
                // inverterType:this.querylist.inverterType,
            })
        },
        openSnDetail(data){
            console.log(data)
            sessionStorage.setItem("selRow_charg_pileType",data.pileType);
            sessionStorage.setItem("selRow_charg_siteid",data.siteIds);
            sessionStorage.setItem("selRow_charg_pileSn",data.pileSn);
            sessionStorage.setItem("selRow_charg_wifi_sn",data.wifiSn);
            // sessionStorage.setItem("selRow_firmId",data.firmIds);
            // sessionStorage.setItem("selRow_sn_type",2);//逆变器
            // sessionStorage.setItem("selRow_phase_type",data.phaseFlag);
            // sessionStorage.setItem("selRow_battery_type",data.batteryFlag);
            // sessionStorage.setItem("selRow_load_type",data.loadFlag);
            sessionStorage.setItem("selRow_charg_siteId",data.siteIds);
            // sessionStorage.setItem("selRow_batteryTypeFlag",data.batteryType);//电池类型
            sessionStorage.setItem("selRow_charg_userId",data.userIds);
            // sessionStorage.setItem("selRow_epsStatus",data.epsStatus);
            
            let url = this.$router.resolve({
                path: "/overview-charg",
            });
            window.open(url.href, '_blank');
        },
        showPvModulesModal(data){
            this.modulesRowData = data
            this.$store.commit('setNewVisiblePvModules',true)
        },
        showGroupModal(data){
            this.groupRowData=data
            this.$store.commit('setNewVisibleGroup',true)
        },
        showRemarkModal(data){
            this.remarkModalWifuSn = data.wifiSN
            this.remarkModalNote = data.note
            this.$store.commit('setNewVisibleRemark',true)
        },
        showFlowModal(data){
            this.flowModalWifuSn = data.wifiSn
            this.$store.commit('setNewVisibleFlow',true)
        },
        returnStatus(flag){
            let code = ''
            if(!this.textDataList){
                return
            }
            this.textDataList.ON_LINE_STATE.forEach(item =>{
                if(item.value == flag){
                    code = item.code
                }
            })
            return code
        },
        async deviceGetPage(){
            this.loading = true
            let params={}
            //电站管理的传参
            if(this.siteId) params.siteId=this.siteId
            if(this.businessId) params.businessId=this.businessId
            if(this.userId) params.userId=this.userId

            let res = await this.API.devchargepileGetPage(Object.assign({},this.querylist,{
                size:this.size,
                current:this.current
            },params))

            this.dataRows = res.rows || []
            this.dataRows.forEach((item,i) => {
                item['wifiSN'] = item.wifiSn
                item['showUpdataFlag'] = false //自定义字段
            })
            this.total = res.total
            this.loading = false

            //升级新增
            // this.updatingSNsArr = ['SC3HTLEMJC']
            this.updatingSNsArr = []
            //启动计时器前，必须清除之前的计时器，避免多个计时器运行
            window.clearTimeout(this.timeOutId)
            //element table的数据渲染要耗时，这里给一个短暂计时器，避免获取更新的wifisn组为空，----暂时没有找到element table数据渲染后的回调钩子，如有，可以替换下面计时器，提高响应效率
            
            this.timeOutId = window.setTimeout(()=>{
                console.log(this.updatingSNsArr,'this.updatingSNsArr')
                if(this.updatingSNsArr.length > 0){
                    this.updateGetUpdateProgressByWifis()
                }
            },0.5*1000)
        },
        async selectCountry(){
            let res = await this.API.selectCountry()
            this.countryList = res || []
        },
        async deviceGetSubGroupName(){
            let res = await this.API.deviceGetSubGroupName()
            this.groupName = res
        },
        async getDictionaryBatch(){
            this.loading = true
            let res = await this.API.getDictionaryBatch({
                dictCodes:'ON_LINE_STATE,INVERTER_TYPES,IS_PUBLIC,SALER_TYPE,INTELBARS_INVERTER_TYPES,WIFI_DEVICE_CHARGE_TYPE,CHARGE_DEVICE_CLASSIFY',
                lang:localStorage.getItem('lan') || 'zh_CN'
            })
            this.textDataList = res || {}
            this.loading = false
            this.deviceGetPage()
        },
        query(){
            this.current = 1
            this.deviceGetPage()
        },
        handleSizeChange(val) {
          this.size = val
          this.current = 1
          this.deviceGetPage()
        },
        handleCurrentChange(val) {
          this.current = val
          this.deviceGetPage()
        },

        //升级
        async updateGetUpdateProgressByWifis(){
            console.log('升级')
            //此方法主作更新的循环机制，用于实时更新更新的进度
            let res = await this.API.updateGetUpdateProgressByWifis({
                wifiSNs:this.updatingSNsArr.join()
            })
            this.doUpdataArr = res!=''?JSON.parse(res):[]
            
            if(this.doUpdataArr.length>0){
                this.doUpdataArr.forEach(item =>{
                    let str = ''
                    let devSn=item.name;
                    let progress=item.value;
                    let successFlag=item.successFlag;

                    if(successFlag=='0'){
                        str = this.$t('devUpgrade.fialUpgrade')
                        this.updatingSNsArr.splice(this.updatingSNsArr.indexOf(devSn),1)
                    }else if(successFlag==2){
                        if(item.value && item.value != '100'){
                            str = this.$t('devUpgrade.download') +  `${progress}%`
                        }else if(item.value == '100'){
                            str = this.$t('devUpgrade.downfinish')
                            this.updatingSNsArr.splice(this.updatingSNsArr.indexOf(devSn),1)
                        }
                    }else if(successFlag==1||successFlag==3){
                        str = this.$t('version.versionAdd.succeed')
                        this.dataRows.forEach(item =>{
                            if(item.wifiSN == devSn){
                                this.$set(item,'updateFlag',0)
                                this.$set(item,'progress',progress)
                                this.$set(item,'updateStatusFlag','1')
                            }
                        })

                        this.updatingSNsArr.splice(this.updatingSNsArr.indexOf(devSn),1)
                    }else if(successFlag==4){
                        str = ' - '
                    }else if(successFlag==5){
                        str = this.$t('devUpgrade.download') + ` 0%`
                    }
                    this.dataRows.forEach(item =>{
                        if(item.wifiSN == devSn){
                            this.$set(item,'progress',str)
                            this.$set(item,'showUpdataFlag',true)
                        }
                    })
                })
                window.clearTimeout(this.timeOutId)
                this.timeOutId = window.setTimeout(()=>{
                    this.updateGetUpdateProgressByWifis()
                },5*1000)
            }
        },
        //初始化列表时获取要升级的wifiSN及详细数据
        returnProgress(data){
            //此方法作用：
            //1、将table列表里面正在更新的数据的wifisn，push到更新的数据里面
            //2、对列表的数据进行判断，初步渲染更新状态

            //【重要】升级表格必要字段：updateStatusFlag updateFlag progress 
            let updateStatusFlag=data.updateStatusFlag;
            let updateFlag=data.updateFlag;
            let progress=data.progress;
            let wifiSN=data.wifiSN;
            // console.log(data, data.wifiSN, data.progress, 'returnProgress')

            //不在线的进度直接显示"-"
            if( data.onLineStatus!=1){
                return ' - '
            }
            
            if(!data.showUpdataFlag){
                if(updateFlag == 1){
                    if(progress==101){
                        if (this.updatingSNsArr.indexOf(wifiSN) == -1) {
                            this.updatingSNsArr.push(wifiSN);
                        }
                        return this.$t('devUpgrade.download') + ' 0%'
                    }else{
                        if(updateStatusFlag=='0'){//0下载失败
                            return this.$t('devUpgrade.fialUpgrade')
                        }else if(updateStatusFlag==2){
                            if (this.updatingSNsArr.indexOf(wifiSN) == -1) {
                                this.updatingSNsArr.push(wifiSN);
                            }
                            if(progress&&progress!=this.$t('devUpgrade.downfinish')&&progress!=100){	
                                return this.$t('devUpgrade.download')+` ${progress}%`
                            }else if(progress==this.$t('devUpgrade.downfinish')||progress==100){
                                return this.$t('devUpgrade.downfinish')
                            }
                            
                        }else if(updateStatusFlag==1){
                            return this.$t('devUpgrade.downfinish')
                        }else if(updateStatusFlag==null){
                            return ' - '
                        }
                    }
                }else if(updateFlag=='0'){
                    if(updateStatusFlag==null){
                        return ' - '
                    }else if(updateStatusFlag=='0'){
                        return this.$t('devUpgrade.fialUpgrade')
                    }else{
                        return this.$t('devUpgrade.downfinish')
                    }
                }else if(updateFlag==null){
                    return ' - '
                }
            }else{
                console.log(data.showUpdataFlag,'showUpdataFlagshowUpdataFlagshowUpdataFlagshowUpdataFlag')
                return data.progress
            }
            
        },
        //取消升级
        async wifiEditEntity(data){
            let res = await this.API.wifiEditEntity({
                id: data.wifiSNId,
                updateFlag: 0,
                updateStatusFlag: 0
            })
            //重置操作时先把该条数据从更新栈里面去除
            this.updatingSNsArr.splice(this.updatingSNsArr.indexOf(data.wifiSN),1)
            this.deviceGetPage()
        },

    },
};
</script>

<style  lang="less" scoped>
.inverter-main-box{
    .hover-a-link:hover{
        text-decoration: underline;
    }
}
</style>
